package algorithm_demo.demo01;

import java.util.Arrays;

/**
 * 冒泡排序
 *
 * @author Api
 * @date 2023/1/25 21:10
 */
public class Code08_BubbleSort {
    public static void main(String[] args) {
        int[] arr = {4, 2, 1, 4, 4, 5, 5, 6, 3, 1};
        bubbleSort(arr);
        System.out.println(Arrays.toString(arr));
    }


    public static void bubbleSort(int[] arr) {
        //临界值
        if (arr == null || arr.length < 2) {
            return;
        }
        /*
         * 0 - N-1
         * 0 - N-2
         * 0 - N-3
         * 0 - N-4
         * 0 - N-5
         * 0 - end
         * */
        int N = arr.length;
        for (int end = N - 1; end >= 0; end--) {
            for (int j = 1; j <= end; j++) {
                if (arr[j-1] > arr[j]){//前一个数字大于后一个数字，则交换
                    swap(arr, j-1, j);
                }
            }
        }
    }

    public static void swap(int[] arr, int i, int j) {
        int temp = arr[j];
        arr[j] = arr[i];
        arr[i] = temp;
    }
}
